<template>
    <view class="container" :class="{ paddingBottomBar: isShowBottomBar }">
        <uni-load-more status="loading" v-if="isLoading"></uni-load-more>
        <view v-else>
            <view class="order-main">
                <view class="order-item product-item">
                    <view class="title-text title-text-flex">
                        <view>收货信息</view>
                    </view>
                    <view class="order-user">
                        <view class="user-info">
                            <view class="user-info-name"
                                ><image src="/pages_supplier/static/icon/map.png"></image>{{ Address.ContactName }}
                                {{ Address.ContactTel }}</view
                            >
                            <text class="user-info-location"
                                >{{ Address.ProvinceName }}{{ Address.CityName }}{{ Address.AreaName
                                }}{{ Address.StreetName }}{{ Address.ContactAddress }}</text
                            >
                        </view>
                    </view>
                </view>
                <view class="order-item product-item">
                    <view class="title-text title-text-flex">
                        <view>物流信息</view>
                    </view>
                    <view class="wuliu_info">
                        <view>
                            <view class="label">配送方式：</view>
                            <view class="value">
                                <view>{{ Address.ExpressName }} {{ Address.ExpressNo }}</view>
                            </view>
                        </view>
                        <view v-if="false">
                            <view class="label">配送员：</view>
                            <view class="value">
                                <view>小张 13399989998</view>
                            </view>
                        </view>
                    </view>
                </view>
                <view class="deliver_product">
                    <view class="deliver_product_list" v-for="(item, index) in SkuList">
                        <view class="no">货号：{{ item.SkuCode }}</view>
                        <view class="list_info">
                            <image :src="easyGetImgUrl(item.V_ProductImg)" mode="aspectFill"></image>
                            <view class="list_info_r">
                                <view class="name text-show-line-2">{{ item.V_ProductName }}</view>
                                <view v-if="item.V_DisplayAttribute || item.V_AttributeNameValue"
                                    >规格：{{
                                        item.V_DisplayAttribute ? item.V_DisplayAttribute : item.V_AttributeNameValue
                                    }}</view
                                >
                                <view class="flex-between"
                                    ><view class="numstrong">数量：{{ item.Amount }}{{ item.UnitName }}</view></view
                                >
                            </view>
                        </view>
                    </view>
                </view>
                <view class="order-item product-item">
                    <view class="title-text title-text-flex">
                        <view>订单信息</view>
                    </view>
                    <view class="order-info">
                        <view class="order-info-item">
                            <text class="label">出库单号：</text>
                            <text class="value">{{ OutModel.StockOutSn }}</text>
                        </view>
                        <view class="order-info-item">
                            <text class="label">下单时间：</text>
                            <text class="value">{{ BuyModel.AddTime }}</text>
                        </view>
                        <view class="order-info-item" v-if="BuyModel.OrderSnList && BuyModel.OrderSnList.length > 0">
                            <view class="label">销售订单：</view>
                            <view class="value flexvalue">
                                <view :style="!showSn ? 'height:36rpx;overflow:hidden' : 'height:auto;'">
                                    <view v-for="(item, index) in BuyModel.OrderSnList">{{ item }}</view>
                                </view>
                                <uni-icons
                                    @click="showSn = !showSn"
                                    :type="showSn ? 'arrowup' : 'arrowdown'"
                                    v-if="BuyModel.OrderSnList.length > 1"
                                    size="20"
                                    customIcons="icon-black"></uni-icons>
                            </view>
                        </view>
                        <view class="order-info-item">
                            <text class="label">采购单号：</text>
                            <text class="value">{{ BuyModel.OrderNo }}</text>
                        </view>
                        <view class="order-info-item">
                            <text class="label">发货时间：</text>
                            <text class="value">{{ OutModel.AddTime }}</text>
                        </view>
                        <view class="order-info-item" v-if="data.Remark">
                            <text class="label">订单备注：</text>
                            <text class="value">{{ data.Remark }}</text>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <view class="footer">
            <!-- <view class="all btn">打印出库单</view> -->
            <view class="btn" @click="print">打印面单</view>
        </view>
        <uni-popup ref="popReturnTip" type="center" :animation="false" :mask-click="true">
            <view class="pop-return-box">
                <view class="bluelist">
                    <view :key="index" v-for="(item, index) in devices">
                        <view class="blue" @click="onConn(item)">{{ item.name }}</view>
                    </view>
                    <view class="bluetip mescroll-upwarp" v-if="bluetipShow"
                        ><view class="mescroll-rotate"></view>搜索中</view
                    >
                    <view class="bluebtn" @click="searchBle">搜索蓝牙</view>
                </view>
            </view>
        </uni-popup>
    </view>
</template>

<script>
var tsc = require("@/pages_supplier/components/gprint/tsc.js")
var esc = require("@/pages_supplier/components/gprint/esc.js")
import { mapGetters } from "vuex"
import storage from "@/uni-sub-base/utils/storage.js"
import { GetBuyOrdStockOut } from "@/pages_supplier/service/api/buyOrder.js"
export default {
    components: {},
    data() {
        return {
            bluetipShow: false,
            showSn: false,
            devices: [],
            currDev: null,
            connId: "",
            buyOrdId: "",
            outId: "",
            isShowBottomBar: false,
            data: {},
            isLoading: false,
            OutModel: {},
            BuyModel: {},
            Address: {},
            SkuList: [],
            devicesData: [],
        }
    },
    onLoad(e) {
        this.buyOrdId = e.buyOrdId
        this.outId = e.outId
        if (storage.getCache("devices")) {
            this.devicesData = storage.getCache("devices")
        }
        // storage.removeCache("devices")
        console.log(this.devicesData)
    },
    mounted() {
        this.getDetail()
        this.isShowBottomBar = true
    },
    methods: {
        print() {
            if (this.devicesData.length > 0) {
                this.initBule()
                // this.senBleLabel()
            } else {
                this.$refs.popReturnTip.open()
            }
        },
        //获取详情
        getDetail() {
            let path = "?buyOrdId=" + this.buyOrdId + "&outId=" + this.outId
            this.isLoading = true
            GetBuyOrdStockOut(path).then((res) => {
                if (res.State == 1) {
                    this.data = res.Data
                    this.BuyModel = res.Data.BuyModel
                    this.OutModel = res.Data.OutModel
                    this.Address = res.Data.BuyModel.Address
                    this.SkuList = res.Data.OutModel.SkuList
                    this.isLoading = false
                }
            })
        },
        destroyed: function () {
            console.log("destroyed----------")
            if (this.connId != "") {
                uni.closeBLEConnection({
                    deviceId: this.connId,
                    success(res) {
                        console.log(res)
                    },
                })
            }
        },
        initBule() {
            var that = this
            uni.openBluetoothAdapter({
                success(res) {
                    console.log("打开 蓝牙模块")
                    console.log(res)
                    uni.getBluetoothAdapterState({
                        success: function (res) {
                            console.log(res)
                            if (res.available) {
                                that.senBleLabel()
                            } else {
                                storage.removeCache("devices")
                                console.log("本机蓝牙不可用")
                            }
                        },
                    })
                },
                fail(errCode) {
                    if (errCode.code == 10001) {
                        that.easyToast("请先开启蓝牙")
                        storage.removeCache("devices")
                    }
                },
            })
        },
        searchBle() {
            var that = this
            that.bluetipShow = true
            console.log("initBule")
            uni.openBluetoothAdapter({
                success(res) {
                    console.log("打开 蓝牙模块")
                    console.log(res)
                    that.onDevice()
                    uni.getBluetoothAdapterState({
                        success: function (res) {
                            console.log(res)
                            if (res.available) {
                                if (res.discovering) {
                                    that.stopFindBule()
                                }
                                //搜索蓝牙
                                //开始搜寻附近的蓝牙外围设备
                                console.log("开始搜寻附近的蓝牙外围设备")
                                uni.startBluetoothDevicesDiscovery({
                                    success(res) {
                                        console.log(res)
                                    },
                                })
                            } else {
                                storage.removeCache("devices")
                                console.log("本机蓝牙不可用")
                            }
                        },
                    })
                },
                fail(errCode) {
                    if (errCode.code == 10001) {
                        that.easyToast("请先开启蓝牙")
                        storage.removeCache("devices")
                    }
                },
            })
        },
        onDevice() {
            console.log("监听寻找到新设备的事件---------------")
            var that = this
            //监听寻找到新设备的事件
            uni.onBluetoothDeviceFound(function (devices) {
                console.log("--------------new-----------------------" + JSON.stringify(devices))
                var re = JSON.parse(JSON.stringify(devices))
                console.log(re.devices[0].name + "  " + re.devices[0].deviceId)
                let name = re.devices[0].name
                if (name != "未知设备" && name != "") {
                    let deviceId = re.devices[0].deviceId
                    that.devices.push({
                        name: name,
                        deviceId: deviceId,
                        services: [],
                    })
                }
                console.log(that.devices)
            })
        },

        stopFindBule() {
            console.log("停止搜寻附近的蓝牙外围设备---------------")
            uni.stopBluetoothDevicesDiscovery({
                success(res) {
                    console.log(res)
                },
            })
        },
        onConn(item) {
            var that = this
            console.log("连接蓝牙---------------" + item.deviceId)
            let deviceId = item.deviceId
            uni.createBLEConnection({
                deviceId: deviceId,
                complete(res) {
                    if (res.errMsg == "createBLEConnection:ok") {
                        that.easyToast("连接蓝牙-[" + item.name + "]--成功")
                        that.connId = deviceId
                        that.currDev = item
                        setTimeout(function () {
                            that.getBLEServices(deviceId)
                        }, 2000)
                    } else {
                        console.log(res)
                    }
                    //连接成功 关闭搜索
                    that.stopFindBule()
                },
                fail(error) {
                    console.log(error)
                },
            })
        },

        getBLEServices(_deviceId) {
            var that = this
            let deviceId = _deviceId
            console.log("获取蓝牙设备所有服务(service)。---------------")

            uni.getBLEDeviceServices({
                // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
                deviceId: deviceId,
                complete(res) {
                    console.log(res)
                    let serviceId = ""

                    for (var s = 0; s < res.services.length; s++) {
                        console.log(res.services[s].uuid)
                        let serviceId = res.services[s].uuid
                        uni.getBLEDeviceCharacteristics({
                            // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
                            deviceId: deviceId,
                            // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
                            serviceId: serviceId,
                            success(res) {
                                var re = JSON.parse(JSON.stringify(res))

                                console.log("deviceId = [" + deviceId + "]  serviceId = [" + serviceId + "]")
                                for (var c = 0; c < re.characteristics.length; c++) {
                                    if (re.characteristics[c].properties.write == true) {
                                        let uuid = re.characteristics[c].uuid
                                        console.log(
                                            " deviceId = [" +
                                                deviceId +
                                                "]  serviceId = [" +
                                                serviceId +
                                                "] characteristics=[" +
                                                uuid,
                                        )

                                        for (var index in that.devices) {
                                            if (that.devices[index].deviceId == deviceId) {
                                                that.devices[index].services.push({
                                                    serviceId: serviceId,
                                                    characteristicId: uuid,
                                                })
                                                break
                                            }
                                        }
                                        console.log(JSON.stringify(that.devices))
                                        storage.setCache("devices", that.devices)
                                        that.devicesData = that.devices
                                    }
                                }
                                that.$refs.popReturnTip.close()
                                that.bluetipShow = false
                            },
                        })
                    }
                },
                fail(res) {
                    console.log(res)
                },
            })
        },
        senBlData(deviceId, serviceId, characteristicId, uint8Array) {
            console.log(
                "************deviceId = [" +
                    deviceId +
                    "]  serviceId = [" +
                    serviceId +
                    "] characteristics=[" +
                    characteristicId +
                    "]",
            )
            var uint8Buf = Array.from(uint8Array)
            function split_array(datas, size) {
                var result = {}
                var j = 0
                for (var i = 0; i < datas.length; i += size) {
                    result[j] = datas.slice(i, i + size)
                    j++
                }
                console.log(result)
                return result
            }
            var sendloop = split_array(uint8Buf, 20)
            // console.log(sendloop.length)
            function realWriteData(sendloop, i) {
                var data = sendloop[i]
                if (typeof data == "undefined") {
                    return
                }
                console.log("第【" + i + "】次写数据" + data)
                var buffer = new ArrayBuffer(data.length)
                var dataView = new DataView(buffer)
                for (var j = 0; j < data.length; j++) {
                    dataView.setUint8(j, data[j])
                }
                uni.writeBLECharacteristicValue({
                    deviceId,
                    serviceId,
                    characteristicId,
                    value: buffer,
                    success(res) {
                        realWriteData(sendloop, i + 1)
                    },
                })
            }
            var i = 0
            realWriteData(sendloop, i)
        },
        senBleLabel() {
            //标签模式
            let currDev = this.devicesData[0]
            let deviceId = currDev.deviceId
            let serviceId = currDev.services[0].serviceId
            let characteristicId = currDev.services[0].characteristicId
            console.log(deviceId)
            console.log(serviceId)
            console.log(characteristicId)
            var command = tsc.jpPrinter.createNew()
            // console.log(command)
            command.setSize(76, 130)
            command.setGap(2)
            command.setCls()
            command.setText(20, 150, "TSS24.BF2", 1, 1, "No." + this.OutModel.StockOutSn)
            // command.setQR(10, 50, "L", 5, "A", "977767937@qq.com")
            command.setBar(20, 200, 128, 120, 0, 2, 2, this.Address.ExpressNo)
            command.setText(20, 370, "TSS24.BF2", 1, 1, "配送单号：" + this.Address.ExpressNo)
            command.setText(20, 500, "TSS24.BF2", 3, 3, "寄")
            command.setText(120, 500, "TSS24.BF2", 1, 1, this.OutModel.SendMan + "    " + this.OutModel.SendTel)
            command.setTextauto(120, 550, "TSS24.BF2", 1, 1, this.OutModel.SendAddress)
            command.setText(20, 700, "TSS24.BF2", 3, 3, "收")
            command.setText(120, 700, "TSS24.BF2", 1, 1, this.Address.ContactName + "    " + this.Address.ContactTel)
            command.setTextauto(120, 750, "TSS24.BF2", 1, 1, this.Address.Address)
            command.setPagePrint()
            this.senBlData(deviceId, serviceId, characteristicId, command.getData())
        },
        goUrl(url) {
            this.easyGoTo(url)
        },
    },
}
</script>

<style lang="scss" scoped>
.container {
    background-color: $uni-bg-color-grey;
}

.order-item {
    background: $color-white;
    margin-bottom: 24rpx;
    // background: red;
}

.product-item {
    padding: $app-page-padding;
    border-radius: 8rpx;

    .title-text {
        display: flex;
        font-weight: 700;
        padding-bottom: 24rpx;
        padding-left: 24rpx;
        padding-right: 24rpx;
        border-bottom: 1rpx solid #ebebeb;
        margin-bottom: 24rpx;
        font-size: 28rpx;
        margin-left: -24rpx;
        margin-right: -24rpx;
        color: $color-gray-1;
    }

    .title-text-flex {
        justify-content: space-between;
        align-items: center;
    }

    .title-text-right {
        display: flex;
        justify-content: flex-end;
        align-items: center;
    }

    .title-text-desc {
        font-size: $font-size-24;
        color: $color-gray-2;
        padding-right: 12rpx;
        font-weight: normal;
    }
}

.product-item-line {
    .title-text {
        border-bottom: none;
        margin-bottom: 0rpx;
    }
}

.order-main {
    padding: $app-page-padding $app-page-padding 0;

    .order-title {
        height: 98rpx;
        padding: $app-page-padding 0;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .order-t-l {
            height: 98rpx;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        .order-header-button {
            width: 158rpx;
            height: 64rpx;
            background: #ffffff;
            border-radius: 32rpx;
            text-align: center;
            line-height: 64rpx;
            color: $app-color-main;
            font-size: $font-size-28;
        }

        text {
            font-weight: 700;
            font-size: $font-size-36;
            color: $color-white;
        }

        view {
            font-size: $font-size-24;
            color: $color-white;
        }
    }

    .order-user {
        // padding: $app-page-padding;
        display: flex;
        flex-direction: row;
        align-items: center;

        .location {
            width: 54rpx;
            height: 54rpx;
            border-radius: 27rpx;
            display: flex;
            justify-content: center;
            align-items: center;
            background: $app-color-main;
            margin-right: 20rpx;
        }

        .user-info {
            display: flex;
            flex: 1;
            display: flex;
            flex-direction: column;

            text {
                color: $app-color-text-mian;
            }

            .user-info-name {
                font-size: $font-size-30;
                font-weight: 700;
                margin-bottom: 12rpx;
                display: flex;
                align-items: center;
                image {
                    width: 32rpx;
                    height: 32rpx;
                    margin-right: 14rpx;
                }
            }

            .user-info-location {
                font-size: $font-size-24;
                line-height: 32rpx;
                color: $color-gray-3;
            }
        }
    }

    .order-items {
        padding: 30rpx $app-page-padding 1rpx;
    }

    .order-info {
        display: flex;
        flex-direction: column;

        .order-info-item {
            padding: 14rpx 0;
            display: flex;
            flex-direction: row;

            text {
                font-size: $font-size-24;
            }

            .label {
                color: $app-color-text-tip;
                margin-right: 10rpx;
                width: 120rpx;
                white-space: nowrap;
                font-size: 24rpx;
            }

            .value {
                word-break: break-all;
                color: $app-color-text-mian;
                font-size: 24rpx;
            }
            .flexvalue {
                flex: 1;
                display: flex;
                justify-content: space-between;
                view {
                    padding-bottom: 5rpx;
                }
            }

            .order-info-image {
                width: 122rpx;
                height: 122rpx;
            }
        }
    }
}

.order-bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 120rpx;
    background: $color-white;
    box-shadow: 0px -2rpx 10rpx 0px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    align-items: center;
    padding: 0 $app-page-padding;
}

.ptb0 {
    padding-bottom: 0 !important;
}
.wuliu_info {
    margin: -24rpx 0;
    & > view {
        display: flex;
        height: 98rpx;
        align-items: center;
    }
    .label {
        font-size: 28rpx;
        color: #999;
        width: 140rpx;
    }
    .color-gray-light {
        color: $color-gray-3;
    }
    .value {
        flex: 1;
        display: flex;
        align-items: center;
        font-size: 28rpx;
        & > view {
            flex: 1;
        }
    }
}
.deliver_product {
    padding: 0 24rpx;
    background: #ffffff;
    border-radius: 8rpx;
    margin-bottom: 24rpx;
    .deliver_product_list {
        padding: 24rpx 0;
        border-bottom: 2rpx solid $uni-border-bottom-color;
        .no {
            font-size: 28rpx;
            color: #0091ff;
        }
        .list_info {
            padding: 16rpx 0;
            display: flex;
            .list_info_r {
                flex: 1;
                display: flex;
                flex-direction: column;
                justify-content: space-around;
                font-size: 24rpx;
                color: $color-gray-3;
                .name {
                    font-size: 26rpx;
                    color: $color-gray-1;
                }
                .numstrong {
                    font-weight: bold;
                    color: #222a42;
                }
            }
            image {
                width: 160rpx;
                height: 160rpx;
                border-radius: 8rpx;
                border: 1rpx solid #f4ea71;
                margin-right: 24rpx;
            }
        }
        .list_info_b {
            font-size: 26rpx;
            color: $color-gray-1;
            font-weight: bold;
            display: flex;
            align-items: center;
            input {
                width: 350rpx;
                height: 64rpx;
                background: #f5f5f5;
                border-radius: 4rpx;
                padding-left: 16rpx;
                font-weight: normal;
                margin-right: 16rpx;
                font-size: 28rpx;
            }
        }
    }
    .deliver_product_list:last-child {
        border: none;
    }
}
.order-state-menu {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;

    .btn {
        margin-left: $app-page-padding;
        height: 58rpx;
        font-size: 24rpx;
        min-width: 100rpx;
    }
    .btn-gray {
        border-color: #222a42;
        color: #222a42;
    }
}
.bigbtn {
    flex: 1;
    justify-content: center;
    .btn {
        width: 304rpx;
        height: 80rpx;
        background: $app-color-main;
        margin: 0;
        border-radius: 40rpx;
        padding: 0;
        font-size: 28rpx;
        margin: 0 24rpx;
        color: #ffffff;
    }
    .btn-gray {
        background: #ffffff;
        border: 1rpx solid $app-color-main;
        color: $app-color-main;
    }
}
.footer {
    width: 750rpx;
    height: 120rpx;
    background: #ffffff;
    box-shadow: 0px -2rpx 6rpx 0px rgba(0, 0, 0, 0.1);
    position: fixed;
    left: 0;
    bottom: 0;
    z-index: 99;
    display: flex;
    justify-content: center;
    align-items: center;
    .btn {
        width: 304rpx;
        height: 80rpx;
        background: $app-color-main;
        border-radius: 40rpx;
        font-size: 28rpx;
        color: #ffffff;
        margin: 0 23rpx;
    }
    .all {
        background: #222a42;
    }
}
.bluelist {
    text-align: center;
    .blue {
        border-radius: 29rpx;
        border: 1rpx solid #0081ff;
        color: #0081ff;
        padding: 10rpx 0;
        margin-bottom: 20rpx;
    }
    .bluebtn {
        width: 304rpx;
        height: 80rpx;
        line-height: 80rpx;
        text-align: center;
        background: $app-color-main;
        border-radius: 40rpx;
        font-size: 28rpx;
        color: #ffffff;
        margin: 0 auto;
    }
}
/*旋转进度条 */
.mescroll-upwarp {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    padding: 10rpx 0;
    color: $color-gray-2;
}
.mescroll-upwarp .mescroll-rotate {
    display: inline-block;
    width: 32rpx;
    height: 32rpx;
    border-radius: 50%;
    border: 2rpx solid gray;
    border-bottom-color: transparent !important; /*已在style设置border-color,此处需加 !important*/
    vertical-align: middle;
    margin-right: 10rpx;
}

/* 旋转动画 */
.mescroll-upwarp .mescroll-rotate {
    animation: mescrollUpRotate 0.6s linear infinite;
}

@keyframes mescrollUpRotate {
    0% {
        transform: rotate(0deg);
    }

    100% {
        transform: rotate(360deg);
    }
}
</style>
